class Game {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.score = 0;
        this.correctAnswers = 0;
        this.currentProblem = null;
        this.lastProblemTime = 0;
        this.problemInterval = 2000;
        this.effect = null;
        this.effectStartTime = 0;
        this.message = null;
        this.messageStartTime = 0;
        this.effectImage = null;
        this.usedCharacters = new Set(); // 记录已使用过的汉字

        // 汉字列表及其拼音
        this.characters = [
            { char: '天', pinyin: 'tiān' }, { char: '地', pinyin: 'dì' }, { char: '人', pinyin: 'rén' },
            { char: '你', pinyin: 'nǐ' }, { char: '我', pinyin: 'wǒ' }, { char: '他', pinyin: 'tā' },
            { char: '一', pinyin: 'yī' }, { char: '二', pinyin: 'èr' }, { char: '三', pinyin: 'sān' },
            { char: '四', pinyin: 'sì' }, { char: '五', pinyin: 'wǔ' }, { char: '上', pinyin: 'shàng' },
            { char: '下', pinyin: 'xià' }, { char: '口', pinyin: 'kǒu' }, { char: '耳', pinyin: 'ěr' },
            { char: '目', pinyin: 'mù' }, { char: '手', pinyin: 'shǒu' }, { char: '足', pinyin: 'zú' },
            { char: '站', pinyin: 'zhàn' }, { char: '坐', pinyin: 'zuò' }, { char: '日', pinyin: 'rì' },
            { char: '月', pinyin: 'yuè' }, { char: '水', pinyin: 'shuǐ' }, { char: '火', pinyin: 'huǒ' },
            { char: '山', pinyin: 'shān' }, { char: '石', pinyin: 'shí' }, { char: '田', pinyin: 'tián' },
            { char: '禾', pinyin: 'hé' }, { char: '对', pinyin: 'duì' }, { char: '云', pinyin: 'yún' },
            { char: '雨', pinyin: 'yǔ' }, { char: '风', pinyin: 'fēng' }, { char: '花', pinyin: 'huā' },
            { char: '鸟', pinyin: 'niǎo' }, { char: '虫', pinyin: 'chóng' }, { char: '六', pinyin: 'liù' },
            { char: '七', pinyin: 'qī' }, { char: '八', pinyin: 'bā' }, { char: '九', pinyin: 'jiǔ' },
            { char: '十', pinyin: 'shí' }, { char: '爸', pinyin: 'bà' }, { char: '妈', pinyin: 'mā' },
            { char: '马', pinyin: 'mǎ' }, { char: '土', pinyin: 'tǔ' }, { char: '不', pinyin: 'bù' },
            { char: '画', pinyin: 'huà' }, { char: '打', pinyin: 'dǎ' }, { char: '棋', pinyin: 'qí' },
            { char: '鸡', pinyin: 'jī' }, { char: '字', pinyin: 'zì' }, { char: '词', pinyin: 'cí' },
            { char: '语', pinyin: 'yǔ' }, { char: '句', pinyin: 'jù' }, { char: '子', pinyin: 'zǐ' },
            { char: '桌', pinyin: 'zhuō' }, { char: '纸', pinyin: 'zhǐ' }, { char: '文', pinyin: 'wén' },
            { char: '数', pinyin: 'shù' }, { char: '学', pinyin: 'xué' }, { char: '音', pinyin: 'yīn' },
            { char: '乐', pinyin: 'yuè' }, { char: '每', pinyin: 'měi' }, { char: '奶', pinyin: 'nǎi' },
            { char: '白', pinyin: 'bái' }, { char: '皮', pinyin: 'pí' }, { char: '小', pinyin: 'xiǎo' },
            { char: '桥', pinyin: 'qiáo' }, { char: '台', pinyin: 'tái' }, { char: '雪', pinyin: 'xuě' },
            { char: '儿', pinyin: 'ér' }, { char: '草', pinyin: 'cǎo' }, { char: '家', pinyin: 'jiā' },
            { char: '是', pinyin: 'shì' }, { char: '车', pinyin: 'chē' }, { char: '羊', pinyin: 'yáng' },
            { char: '走', pinyin: 'zǒu' }, { char: '也', pinyin: 'yě' }, { char: '秋', pinyin: 'qiū' },
            { char: '气', pinyin: 'qì' }, { char: '树', pinyin: 'shù' }, { char: '叶', pinyin: 'yè' },
            { char: '片', pinyin: 'piàn' }, { char: '大', pinyin: 'dà' }, { char: '飞', pinyin: 'fēi' },
            { char: '会', pinyin: 'huì' }, { char: '个', pinyin: 'gè' }, { char: '的', pinyin: 'de' },
            { char: '船', pinyin: 'chuán' }, { char: '两', pinyin: 'liǎng' }, { char: '头', pinyin: 'tóu' },
            { char: '在', pinyin: 'zài' }, { char: '里', pinyin: 'lǐ' }, { char: '看', pinyin: 'kàn' },
            { char: '见', pinyin: 'jiàn' }, { char: '闪', pinyin: 'shǎn' }, { char: '星', pinyin: 'xīng' },
            { char: '江', pinyin: 'jiāng' }, { char: '南', pinyin: 'nán' }, { char: '可', pinyin: 'kě' },
            { char: '采', pinyin: 'cǎi' }, { char: '莲', pinyin: 'lián' }, { char: '鱼', pinyin: 'yú' },
            { char: '东', pinyin: 'dōng' }, { char: '西', pinyin: 'xī' }, { char: '北', pinyin: 'běi' },
            { char: '尖', pinyin: 'jiān' }, { char: '说', pinyin: 'shuō' }, { char: '春', pinyin: 'chūn' },
            { char: '青', pinyin: 'qīng' }, { char: '娃', pinyin: 'wá' }, { char: '夏', pinyin: 'xià' },
            { char: '弯', pinyin: 'wān' }, { char: '就', pinyin: 'jiù' }, { char: '冬', pinyin: 'dōng' },
            { char: '男', pinyin: 'nán' }, { char: '女', pinyin: 'nǚ' }, { char: '开', pinyin: 'kāi' },
            { char: '关', pinyin: 'guān' }, { char: '正', pinyin: 'zhèng' }, { char: '包', pinyin: 'bāo' },
            { char: '尺', pinyin: 'chǐ' }, { char: '作', pinyin: 'zuò' }, { char: '业', pinyin: 'yè' },
            { char: '本', pinyin: 'běn' }, { char: '笔', pinyin: 'bǐ' }, { char: '刀', pinyin: 'dāo' },
            { char: '课', pinyin: 'kè' }, { char: '早', pinyin: 'zǎo' }, { char: '校', pinyin: 'xiào' },
            { char: '明', pinyin: 'míng' }, { char: '力', pinyin: 'lì' }, { char: '尘', pinyin: 'chén' },
            { char: '从', pinyin: 'cóng' }, { char: '众', pinyin: 'zhòng' }, { char: '双', pinyin: 'shuāng' },
            { char: '木', pinyin: 'mù' }, { char: '林', pinyin: 'lín' }, { char: '森', pinyin: 'sēn' },
            { char: '条', pinyin: 'tiáo' }, { char: '心', pinyin: 'xīn' }, { char: '升', pinyin: 'shēng' },
            { char: '国', pinyin: 'guó' }, { char: '旗', pinyin: 'qí' }, { char: '中', pinyin: 'zhōng' },
            { char: '红', pinyin: 'hóng' }, { char: '歌', pinyin: 'gē' }, { char: '起', pinyin: 'qǐ' },
            { char: '么', pinyin: 'me' }, { char: '美', pinyin: 'měi' }, { char: '丽', pinyin: 'lì' },
            { char: '立', pinyin: 'lì' }, { char: '午', pinyin: 'wǔ' }, { char: '晚', pinyin: 'wǎn' },
            { char: '昨', pinyin: 'zuó' }, { char: '今', pinyin: 'jīn' }, { char: '年', pinyin: 'nián' },
            { char: '影', pinyin: 'yǐng' }, { char: '前', pinyin: 'qián' }, { char: '后', pinyin: 'hòu' },
            { char: '黑', pinyin: 'hēi' }, { char: '狗', pinyin: 'gǒu' }, { char: '左', pinyin: 'zuǒ' },
            { char: '右', pinyin: 'yòu' }, { char: '它', pinyin: 'tā' }, { char: '好', pinyin: 'hǎo' },
            { char: '朋', pinyin: 'péng' }, { char: '友', pinyin: 'yǒu' }, { char: '比', pinyin: 'bǐ' },
            { char: '尾', pinyin: 'wěi' }, { char: '巴', pinyin: 'bā' }, { char: '谁', pinyin: 'shéi' },
            { char: '长', pinyin: 'cháng' }, { char: '短', pinyin: 'duǎn' }, { char: '把', pinyin: 'bǎ' },
            { char: '伞', pinyin: 'sǎn' }, { char: '兔', pinyin: 'tù' }, { char: '最', pinyin: 'zuì' },
            { char: '公', pinyin: 'gōng' }, { char: '写', pinyin: 'xiě' }, { char: '诗', pinyin: 'shī' },
            { char: '点', pinyin: 'diǎn' }, { char: '要', pinyin: 'yào' }, { char: '过', pinyin: 'guò' },
            { char: '给', pinyin: 'gěi' }, { char: '当', pinyin: 'dāng' }, { char: '串', pinyin: 'chuàn' },
            { char: '们', pinyin: 'men' }, { char: '以', pinyin: 'yǐ' }, { char: '成', pinyin: 'chéng' },
            { char: '彩', pinyin: 'cǎi' }, { char: '半', pinyin: 'bàn' }, { char: '空', pinyin: 'kōng' },
            { char: '问', pinyin: 'wèn' }, { char: '到', pinyin: 'dào' }, { char: '方', pinyin: 'fāng' },
            { char: '没', pinyin: 'méi' }, { char: '更', pinyin: 'gèng' }, { char: '绿', pinyin: 'lǜ' },
            { char: '出', pinyin: 'chū' }, { char: '睡', pinyin: 'shuì' }, { char: '那', pinyin: 'nà' },
            { char: '海', pinyin: 'hǎi' }, { char: '真', pinyin: 'zhēn' }, { char: '老', pinyin: 'lǎo' },
            { char: '师', pinyin: 'shī' }, { char: '吗', pinyin: 'ma' }, { char: '同', pinyin: 'tóng' },
            { char: '什', pinyin: 'shén' }, { char: '才', pinyin: 'cái' }, { char: '亮', pinyin: 'liàng' },
            { char: '时', pinyin: 'shí' }, { char: '候', pinyin: 'hòu' }, { char: '觉', pinyin: 'jué' },
            { char: '得', pinyin: 'dé' }, { char: '自', pinyin: 'zì' }, { char: '己', pinyin: 'jǐ' },
            { char: '很', pinyin: 'hěn' }, { char: '穿', pinyin: 'chuān' }, { char: '衣', pinyin: 'yī' },
            { char: '服', pinyin: 'fú' }, { char: '快', pinyin: 'kuài' }, { char: '蓝', pinyin: 'lán' },
            { char: '由', pinyin: 'yóu' }, { char: '笑', pinyin: 'xiào' }, { char: '着', pinyin: 'zhe' },
            { char: '向', pinyin: 'xiàng' }, { char: '和', pinyin: 'hé' }, { char: '贝', pinyin: 'bèi' },
            { char: '挂', pinyin: 'guà' }, { char: '活', pinyin: 'huó' }, { char: '金', pinyin: 'jīn' },
            { char: '哥', pinyin: 'gē' }, { char: '姐', pinyin: 'jiě' }, { char: '弟', pinyin: 'dì' },
            { char: '叔', pinyin: 'shū' }, { char: '爷', pinyin: 'yé' }, { char: '群', pinyin: 'qún' },
            { char: '竹', pinyin: 'zhú' }, { char: '牙', pinyin: 'yá' }, { char: '用', pinyin: 'yòng' },
            { char: '几', pinyin: 'jǐ' }, { char: '步', pinyin: 'bù' }, { char: '为', pinyin: 'wéi' },
            { char: '参', pinyin: 'cān' }, { char: '加', pinyin: 'jiā' }, { char: '洞', pinyin: 'dòng' },
            { char: '乌', pinyin: 'wū' }, { char: '鸦', pinyin: 'yā' }, { char: '处', pinyin: 'chù' },
            { char: '找', pinyin: 'zhǎo' }, { char: '办', pinyin: 'bàn' }, { char: '旁', pinyin: 'páng' },
            { char: '许', pinyin: 'xǔ' }, { char: '法', pinyin: 'fǎ' }, { char: '放', pinyin: 'fàng' },
            { char: '进', pinyin: 'jìn' }, { char: '高', pinyin: 'gāo' }, { char: '住', pinyin: 'zhù' },
            { char: '孩', pinyin: 'hái' }, { char: '玩', pinyin: 'wán' }, { char: '吧', pinyin: 'ba' },
            { char: '发', pinyin: 'fā' }, { char: '芽', pinyin: 'yá' }, { char: '爬', pinyin: 'pá' },
            { char: '呀', pinyin: 'ya' }, { char: '久', pinyin: 'jiǔ' }, { char: '回', pinyin: 'huí' },
            { char: '全', pinyin: 'quán' }, { char: '变', pinyin: 'biàn' }, { char: '工', pinyin: 'gōng' },
            { char: '厂', pinyin: 'chǎng' }, { char: '医', pinyin: 'yī' }, { char: '院', pinyin: 'yuàn' },
            { char: '生', pinyin: 'shēng' }];

        // 初始化音效
        this.correctSound = new Audio('../res/success.mp3');
        this.wrongSound = new Audio('../res/fail.mp3');
        
        // 预加载GIF图片
        this.successGif = new Image();
        this.successGif.src = '../res/success.gif';
        this.failGif = new Image();
        this.failGif.src = '../res/fail.gif';

        this.canvas.addEventListener('click', this.handleClick.bind(this));
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const simulatedClick = new MouseEvent('click', {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            this.canvas.dispatchEvent(simulatedClick);
        });
        requestAnimationFrame(this.gameLoop.bind(this));
    }

    generateProblem() {
        // 如果所有汉字都已使用过，重置记录
        if (this.usedCharacters.size >= this.characters.length) {
            this.usedCharacters.clear();
        }

        // 随机选择一个未使用过的汉字
        let availableChars = this.characters.filter(char => !this.usedCharacters.has(char.char));
        const index = Math.floor(Math.random() * availableChars.length);
        const correct = availableChars[index];
        
        // 记录已使用的汉字
        this.usedCharacters.add(correct.char);

        // 生成三个错误选项
        let options = [correct.pinyin];
        const used = new Set([index]);

        while (options.length < 4) {
            const wrongIndex = Math.floor(Math.random() * this.characters.length);
            if (!used.has(wrongIndex)) {
                used.add(wrongIndex);
                options.push(this.characters[wrongIndex].pinyin);
            }
        }

        // 随机排序选项
        options = options.sort(() => Math.random() - 0.5);

        return {
            character: correct.char,
            options,
            correctPinyin: correct.pinyin,
            x: this.canvas.width / 2,
            y: 100
        };
    }

    showEffect(type, message) {
        this.effect = type;
        this.effectStartTime = Date.now();
        this.message = message;
        this.messageStartTime = Date.now();
        
        // 设置对应的GIF图片
        this.effectImage = type === 'fireworks' ? this.successGif : this.failGif;
        
        // 播放音效
        if (type === 'fireworks') {
            this.correctSound.play();
        } else {
            this.wrongSound.play();
        }
    }

    handleClick(event) {
        if (!this.currentProblem || this.effect) return;

        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;

        const optionHeight = 40;
        const optionWidth = 150;
        const optionSpacing = 20;
        const totalWidth = (optionWidth + optionSpacing) * 4 - optionSpacing;
        let startX = (this.canvas.width - totalWidth) / 2;

        for (let i = 0; i < 4; i++) {
            const optionX = startX + (optionWidth + optionSpacing) * i;
            const optionY = 200;

            if (x >= optionX && x <= optionX + optionWidth &&
                y >= optionY && y <= optionY + optionHeight) {
                if (this.currentProblem.options[i] === this.currentProblem.correctPinyin) {
                    this.score += 10;
                    this.correctAnswers++;
                    this.showEffect('fireworks', '你最棒了！');
                } else {
                    this.showEffect('explosion', '继续努力哟！');
                }
                this.currentProblem = null;
                break;
            }
        }
    }

    gameLoop(timestamp) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

        if (this.correctAnswers >= 10) {
            this.ctx.fillStyle = 'black';
            this.ctx.font = '30px Arial';
            this.ctx.textAlign = 'center';
            this.ctx.fillText('恭喜你闯关成功！', this.canvas.width / 2, this.canvas.height / 2);
            document.getElementById('score').textContent = `最终得分: ${this.score}`;
            return;
        }

        if (this.effect) {
            const effectDuration = 2000;
            const effectCenter = { x: this.canvas.width / 2, y: this.canvas.height / 2 };
            
            // 显示GIF图片
            if (this.effectImage) {
                const imageSize = 200;
                this.ctx.drawImage(
                    this.effectImage,
                    effectCenter.x - imageSize / 2,
                    effectCenter.y - imageSize / 2,
                    imageSize,
                    imageSize
                );
            }

            // 显示文字提示
            if (this.message) {
                this.ctx.fillStyle = 'black';
                this.ctx.font = '24px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(this.message, this.canvas.width / 2, this.canvas.height / 2 - 120);
            }

            if (Date.now() - this.effectStartTime >= effectDuration) {
                this.effect = null;
                this.message = null;
                this.effectImage = null;
            }
        } else {
            if (!this.currentProblem) {
                this.currentProblem = this.generateProblem();
            }

            if (this.currentProblem) {
                // 绘制汉字
                this.ctx.fillStyle = 'black';
                this.ctx.font = '72px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(this.currentProblem.character, 
                    this.currentProblem.x, this.currentProblem.y);

                // 绘制拼音选项
                this.ctx.font = '24px Arial';
                const optionHeight = 40;
                const optionWidth = 150;
                const optionSpacing = 20;
                const totalWidth = (optionWidth + optionSpacing) * 4 - optionSpacing;
                let startX = (this.canvas.width - totalWidth) / 2;

                for (let i = 0; i < 4; i++) {
                    const x = startX + (optionWidth + optionSpacing) * i;
                    const y = 200;

                    this.ctx.fillStyle = '#4CAF50';
                    this.ctx.fillRect(x, y, optionWidth, optionHeight);
                    this.ctx.fillStyle = 'white';
                    this.ctx.fillText(this.currentProblem.options[i], 
                        x + optionWidth/2, y + optionHeight/2 + 8);
                }
            }
        }

        document.getElementById('score').textContent = `得分: ${this.score}`;
        requestAnimationFrame(this.gameLoop.bind(this));
    }
}

new Game();